package com.hoongs.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hoongs.v1.entity.Cart;
import com.hoongs.v1.entity.CartProduct;
import com.hoongs.v1.entity.Product;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.mapper.CartMapper;
import com.hoongs.v1.mapper.ProductMapper;
import com.hoongs.v1.mapper.UserMapper;
import com.hoongs.v1.service.CartService;
import com.hoongs.v1.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private UserMapper userMapper;


    /**
     * 根据用户查询所有购物车数据
     *
     * @param token
     * @return
     */
    @Override
    public Result selectListByUser(String token) {
        User user = UserServiceImpl.getUserInfoByToken(token, userMapper);
        if (user == null) return Result.opError("请先登录！");
        QueryWrapper<Cart> wrapper = new QueryWrapper();
        wrapper.eq("user_id", user.getId()).orderByDesc("create_time");
        List<Cart> list = cartMapper.selectList(wrapper);
        List<CartProduct> results = new ArrayList<>();
        for (Cart cartItem : list) {
            Product product = productMapper.selectById(cartItem.getProductId());
            CartProduct cartProduct = new CartProduct();
            results.add(cartProduct.fromProduct(cartItem, product));
        }
        return Result.success(results);
    }


    /**
     * 根据用户id更新购物车数据
     *
     * @param id
     * @param productId
     * @param number
     * @param token
     * @return
     */
    @Override
    public Result updateCartByUser(String id, String productId, BigDecimal number, String token) {
        // 数量小于或等于0时，直接从购物车中删除商品
        if (number.compareTo(BigDecimal.valueOf(0)) != 1) {
            return this.removeFromCart(id, token);
        }
        User user = UserServiceImpl.getUserInfoByToken(token, userMapper);
        if (user == null) return Result.opError("请先登录！");
        Cart cart = new Cart();
        cart.setProductId(productId);
        cart.setNumber(number);
        cart.setUserId(user.getId());
        cart.setUserName(user.getUsername());

        if (StringUtils.isNotBlank(id)) {
            cart.setId(id);
            return this.update(cart);
        } else {
            List<Cart> list = cartMapper.selectList(new QueryWrapper<Cart>().eq("user_id", user.getId()).eq("product_id", productId));
            if (list.size() > 0) {
                cart.setId(list.get(0).getId());
                return this.update(cart);
            } else {
                return this.add(cart);
            }
        }
    }


    @Override
    public Result removeFromCart(String id, String token) {
        User user = UserServiceImpl.getUserInfoByToken(token, userMapper);
        if (user == null) return Result.opError("请先登录！");
        Cart cart = cartMapper.selectById(id);
        if (cart.getUserId().equals(user.getId())) {
            if (cartMapper.deleteById(id) == 1) {
                return Result.opSuccess();
            } else {
                return Result.opError();
            }
        } else {
            return Result.opError("您无权操作此购物车订单！");
        }
    }


    @Override
    public Result updateListByUser(ArrayList<Cart> cartList, String token) {
        User user = UserServiceImpl.getUserInfoByToken(token, userMapper);
        if (user == null) return Result.opError("请先登录！");
        for (Cart cartItem : cartList) {
            if (StringUtils.isNotBlank(cartItem.getId())) {
                this.update(cartItem);
            } else {
                List<Cart> list = cartMapper.selectList(new QueryWrapper<Cart>().eq("user_id", user.getId()).eq("product_id", cartItem.getProductId()));
                if (list.size() > 0) {
                    cartItem.setId(list.get(0).getId());
                    this.update(cartItem);
                } else {
                    this.add(cartItem);
                }
            }
        }
        return null;
    }

    @Override
    public Result add(Cart cart) {
        if (cartMapper.insert(cart) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result remove(String id) {
        if (!findCartById(id)) return Result.opError("没有找到该购物车订单！");
        if (cartMapper.deleteById(id) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result update(Cart cart) {
        if (!findCartById(cart.getId())) return Result.opError("没有找到该购物车订单！");
        if (cartMapper.updateById(cart) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result selectPageList(Integer page, Integer size, String userId, String userName) {
        return null;
    }

    /**
     * 根据Id查询购物车订单是否存在
     */
    public Boolean findCartById(String id) {
        Cart cart = cartMapper.selectById(id);
        return cart != null;
    }
}
